const { ObjectId } = require('mongodb');
const userCollection = 'userProfile';
const blogCollection = 'blog';
const commentCollection = 'comment';
const secondCommentCollection = 'secondComment';

const getUserById = (findData, getCollectionCounts) => async (req, res) => {
    const { _id } = req.query;
    const userId = ObjectId(_id);
    const [user] = await findData({ collection: userCollection, find: { _id: userId } });
    //blogCount 
    const blogCount = await getCollectionCounts({ collection: blogCollection, find: { userId, status: '公开' } });
    user.blogCount = blogCount;
    //blog
    const blogs = await findData({
        collection: blogCollection, find: { userId, status: '公开' }, limit: 5, sort: { _id: -1 }
    })
    user.blogs = blogs
    const commentCount = await getCollectionCounts({ collection: commentCollection, find: { senderId: userId } });
    const secondCommentCount = await getCollectionCounts({ collection: secondCommentCollection, find: { senderId: userId } });
    user.commentCount = commentCount + secondCommentCount;
    if (user) {
        console.log("user:", user);
        res.json({ message: '用户获取成功', code: 0, user });
    }

}

const queryUser = (findData, getCollectionCounts) => async (req, res) => {
    const { limit = 20, skip = 0, sort = { _id: -1 } } = req.payload;
    const find = {
        role: { $lt: 2 }
    }
    //权限小于2的用户
    const users = await findData({
        collection: userCollection,
        limit, skip, sort, find,
        project: { 'password': 0 }
    })
    const count = await getCollectionCounts({ collection: userCollection, find });
    res.json({ count, users });
}

const updateUserRole = (updateOne) => async (req, res) => {
    const { _id, role } = req.payload;
    const update = await updateOne({ collection: userCollection, _id, data: { role, lastUpdate: Date.now() } });
    if (update) {
        res.json({ code: 0, message: '权限更改成功' });
    }
}

module.exports = { getUserById, queryUser, updateUserRole }